﻿using AutoMapper;
using Finance.Api.Write.Applications.Commands.财务管理.Refunds;
using Finance.Domain;
using Finance.ErrorCode;
using Finance.Infrastructure;
using MediatR;
using System.Security.Claims;

namespace Finance.Api.Write.Applications.CommandHands.财务管理.Refunds
{
    public class RefundUpdataCommandHandler : IRequestHandler<RefundUpdataCommand, ApiResult<int>>
    {
        private readonly SqlsugarDb<Refund> db;
        private readonly IMapper mapper;
        private readonly IHttpContextAccessor httpContextAccessor;

        public RefundUpdataCommandHandler(SqlsugarDb<Refund> db, IMapper mapper, IHttpContextAccessor httpContextAccessor)
        {
            this.db = db;
            this.mapper = mapper;
            this.httpContextAccessor = httpContextAccessor;
        }

        public async Task<ApiResult<int>> Handle(RefundUpdataCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            try
            {
                var entity = await db.FirstQuery().FirstAsync(x => x.Id == request.Id);
                if (entity == null)
                {
                    result.message = "查无数据";
                    result.Code = Enumcode.fail;
                }
                entity = mapper.Map(request, entity);
                entity.UpdateTime = DateTime.Now;
                entity.UpdateName = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.Name)?.Value;
                entity.LoginId = Convert.ToInt32(httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
                var updataRefund = await db.Updata(entity);
                if (updataRefund > 0)
                {
                    result.message = "收款信息修改成功";
                    result.data = 1;
                    result.Code = Enumcode.ok;
                }
                else
                {
                    result.message = "收款信息修改失败";
                    result.data = 0;
                    result.Code = Enumcode.fail;
                }

            }
            catch (Exception ex)
            {
                result.message=ex.Message;
                result.Code = Enumcode.fail;
                result.data = 0;
                
            }
          


                return await Task.FromResult(result);
        }
    }
}
